package com.freewater.springboot.demo.validation;

import org.jetbrains.annotations.NotNull;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class PersonValidator implements Validator {

    @Override
    public boolean supports(@NotNull Class<?> clazz) {
        return Person.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(@NotNull Object target, @NotNull Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.empty");
        Person person = (Person) target;
        final int age = person.getAge();
        if (age < 0) {
            errors.rejectValue("age", "negative.value");
        } else if (age > 110) {
            errors.rejectValue("age", "too.darn.old");
        }
    }
}
